package net.zhangbaolin.systemadmin.service.impl;

import net.zhangbaolin.systemadmin.dao.PermissionDao;
import net.zhangbaolin.systemadmin.dao.UserDao;
import net.zhangbaolin.systemadmin.entity.Login;
import net.zhangbaolin.systemadmin.entity.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    UserDao userDao;

    @Resource
    PermissionDao permissionDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //从数据库中查找信息
        User user = userDao.getUserByUsername(username);
        //判断用户是否存在
        if(Objects.isNull(user)){
            throw new UsernameNotFoundException("用户名不存在");
        }
        // 授权
        List<String> list = permissionDao.selectPermsByRole(user.getId());
        List<GrantedAuthority> gaList = list.stream()
                .map(SimpleGrantedAuthority::new) // create a new SimpleGrantedAuthority for each string
                .collect(Collectors.toList());

        //返回用户信息
        return new Login(user,gaList);
    }
}
